package com.zhixun.zhlq.controller;


import com.zhixun.zhlq.entity.SysLogsEntity;
import com.zhixun.zhlq.entity.SysUserEntity;
import com.zhixun.zhlq.service.SysLogsService;
import com.zhixun.zhlq.utils.OsAndBrowserUtil;
import com.zhixun.zhlq.utils.ShiroUtils;


import com.zhixun.zhlq.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;


/**
 * @author eollse
 */
@Controller
public class BaseController {
    @Autowired
    private SysLogsService sysLogsService;

    public SysUserEntity getUser() {
        return ShiroUtils.getUser();
    }

    public Long getUserId() {
        return getUser().getId();
    }

    public String getUsername() {
        return getUser().getUsername();
    }


    /**
     * 日志数据装配
     *
     * @param request
     * @param action
     * @param msg
     * @param userId
     * @param nickName
     * @return
     */
    public SysLogsEntity setLogs(HttpServletRequest request, String action, String msg, Long userId, String nickName) {
        String clientOrigin = "99";
        String ip = null;
        String os = null;
        String browser = null;
        if (request != null) {
            OsAndBrowserUtil osAndBrowser = OsAndBrowserUtil.getOSAndBrowser(request);
            String clintOriginKey = "CLIENT-ORIGIN";
            if (!StringUtil.isEmpty(request.getHeader(clintOriginKey))) {
                clientOrigin = request.getHeader(clintOriginKey);
            }
            ip = osAndBrowser.getIP();
            os = osAndBrowser.getOs();
            browser = osAndBrowser.getBrowser();
        }
        SysLogsEntity logs = new SysLogsEntity(action, msg, ip, os, browser, clientOrigin, userId, nickName);
        return logs;
    }

    public void saveLogs(SysLogsEntity logs) {
        sysLogsService.save(logs);
    }


}